package com.bradz.mytv;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class activityAddChannel extends ListActivity{
	/** Called when the activity is first created. */
    private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }
    private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;
    private List<String> directoryEntries = new ArrayList<String>();
    private ArrayList<File> episode_directories = new ArrayList<File>();
    private File currentDirectory = new File("/");
    private applicationGlobalVars globals;
    private classChannelDatabase channel_database = new classChannelDatabase(this);
    private int channel_number;
    public String path;
    File selected;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        selected = null;
        Intent thisIntent = getIntent();
        channel_number = thisIntent.getIntExtra("channel_id",1);
        ArrayList<String> old_paths = new ArrayList<String>(channel_database.get_channel_paths(channel_number));
        for(String file:old_paths){
        	episode_directories.add(new File(file));
        }
        globals = ((applicationGlobalVars) this.getApplication());
        browseToRoot();
        //navigate_channels_title
}

//The back button quits out of the application. This shouldn't happen
@Override
public void onBackPressed() {}

public void initialize_buttons(){
	final Button button_done = (Button) findViewById(R.id.done_channel);
	button_done.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	if(!episode_directories.isEmpty()){
        		try{
        			Intent thisIntent = getIntent();
        			int _id = thisIntent.getIntExtra("channel_id",1);
        			for(File file: episode_directories){
        				if(!channel_database.return_used_episode_path(_id, file.getAbsolutePath().replace("'","''"))){
        					channel_database.add_channel_episodes(_id, file.getAbsolutePath().replace("'","''"));
        				}
        			}
        			globals.set_network_loaded(false);
        			//Intent myIntent = new Intent(getBaseContext(), currentChannels.class);
        			//startActivity(myIntent);
        			finish();
        		}catch(Exception e){
        			new AlertDialog.Builder(activityAddChannel.this)
                    .setTitle("Error")
                    .setMessage(e.getMessage())
                    .create()
                    .show();
        		}
        	}else{
        		new AlertDialog.Builder(activityAddChannel.this)
                .setTitle("Error")
                .setMessage("You have to select at least one folder to make your channel")
                .create()
                .show();
        	}
        }
    });
}

/**
 * This function browses to the
 * root-directory of the file-system.
 */
private void browseToRoot() {
    browseTo(new File("/mnt"));
}

/**
 * This function browses up one level
 * according to the field: currentDirectory
 */
private void upOneLevel(){
        if(this.currentDirectory.getParent() != null)
                this.browseTo(this.currentDirectory.getParentFile());
}

private void browseTo(final File aDirectory){
    if (aDirectory.isDirectory()){
            this.currentDirectory = aDirectory;
            fill(aDirectory.listFiles());
    }
}

private void fill(File[] files){
	this.directoryEntries.clear();
	// Add the "." and the ".." == 'Up one level'
	try {
		Thread.sleep(10);
	} catch (InterruptedException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
    }
    this.directoryEntries.add(".");
    if(this.currentDirectory.getParent() != null){
                this.directoryEntries.add("..");
    }
        switch(this.displayMode){
        	case ABSOLUTE:
        		if(files != null){
        			for (File file : files){
        				if(file!=null){
        					if (!episode_directories.contains(file)){
        						this.directoryEntries.add(file.getPath());
        					}
                        }
                     }
                 }
                break;
        	case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
        		int currentPathStringLength = this.currentDirectory.getAbsolutePath().length();
                if(files != null){
                	for (File file : files){
                		if(file!=null){
                			if (!episode_directories.contains(file)){
                				this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLength));
                			}
                        }
                    }
                 }
                 break;
        }
        
        Collections.sort(this.directoryEntries);
        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                        R.layout.file_row, this.directoryEntries);
        this.setContentView(R.layout.activity_add_channel);           
        
        ListView fileList = (ListView) findViewById(android.R.id.list);
        TextView folder_selected_text,navigate_channel_title;
        navigate_channel_title = (TextView) findViewById(R.id.navigate_channels_title);
        folder_selected_text= (TextView) findViewById(R.id.folder_selected_text);
        
        navigate_channel_title.setText(channel_database.get_channel_name(channel_number));
        folder_selected_text.setText(this.currentDirectory.getAbsolutePath());
        
        Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-Book.otf");
        navigate_channel_title.setTypeface(font);
        font = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-BookItalic.otf");
        folder_selected_text.setTypeface(font);
        folder_selected_text.setMovementMethod(new ScrollingMovementMethod());
        
        set_folder_list_text();
        initialize_buttons();
        path = this.currentDirectory.getAbsolutePath();
        fileList.setAdapter(directoryList);
        

        }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(this.currentDirectory.getParent() == null){
                    moveTaskToBack(true);
            }else{
                    this.upOneLevel();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
 
@Override    
protected void onListItemClick(ListView l, View v, int position, long id) {
        String selectedFileString = this.directoryEntries.get(position);
        if (selectedFileString.equals(".")) {
                // Refresh
                this.browseTo(this.currentDirectory);
        } else if(selectedFileString.equals("..")){
                this.upOneLevel();
        } else {
                File clickedFile = null;
                switch(this.displayMode){
                        case RELATIVE:
                                clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(position));
                                break;
                        case ABSOLUTE:
                                clickedFile = new File(this.directoryEntries.get(position));
                                break;
                }
                if(clickedFile.isDirectory() && folder_has_folder(clickedFile)){
                    this.browseTo(clickedFile);
                }else if (clickedFile.isDirectory() && !folder_has_folder(clickedFile)){
                	try{
                		episode_directories.add(clickedFile);
                    	fill(this.currentDirectory.listFiles());
                	}catch(Exception e){
            			new AlertDialog.Builder(activityAddChannel.this)
                        .setTitle("Error")
                        .setMessage(e.getMessage())
                        .show();
            		}
                	
                }
        }
}

//Check to see if the folder has any folder children or not
public boolean folder_has_folder(File parent_file){
	boolean folder_flag = false;
	if(parent_file.listFiles() != null){
		File check_file;
		for(int i = 0; i < parent_file.listFiles().length;i++){
			check_file = new File((parent_file.listFiles())[i].getAbsolutePath());
			if (check_file.isDirectory()){
				folder_flag = true;
			}
		}
	}else{
		Log.i("activityAddChannel - folder_has_folder","Nothing in folder");
	}
	
	return folder_flag;
}

public void set_folder_list_text(){
	String current_folders="";
	for(File files: episode_directories){
		current_folders+=files.getName() +"\n";
	}
	TextView someText = (TextView) findViewById(R.id.folder_current_text);
	someText.setMovementMethod(new ScrollingMovementMethod());
    someText.setText(current_folders);
}

}
